/**
 * Copyright: Copyright (c) 2012
 * Company:anhosi.com
 * @author lifuyu
 * @date Jul 7, 2012
 * @version V1.0
 *
 * @Description: 
 */
package com.microcm.common;

import java.io.File;

import org.apache.lucene.search.IndexSearcher;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.microcm.system.cache.SystemCacheKeeper;
import com.microcm.system.dao.SystemDao;
import com.microcm.system.utils.IndexSearcherHolder;
import com.microcmframework.core.context.AppContext;

/**
 * @author kansum
 * 
 */
public class SystemToolkit
{
	private static WebApplicationContext ctx;

	private static SystemDao systemDao = null;

	private static SystemCacheKeeper systemCacheKeeper = null;

	static
	{
		ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(AppContext.getInstance().getServletContext());
		systemDao = (SystemDao) ctx.getBean("systemDao");
		systemCacheKeeper = (SystemCacheKeeper) ctx.getBean("systemCacheKeeper");
	}

	/**
	 * 获取Spring的bean
	 * 
	 * @param beanId
	 * @return
	 */
	public static Object getBean(String beanId)
	{
		return ctx.getBean(beanId);
	}

	/**
	 * 获取不同类型的唯一的序列号
	 * 
	 * @author：lifuyu
	 * @param sType
	 *            系列类型
	 * @param staff
	 *            前缀
	 * @param len
	 *            长度
	 * @return
	 */
	public static String getSerialNo(String sType, String staff, int len)
	{
		String serialNo = systemDao.generateSerialNo(sType, staff, len);
		return serialNo;
	}

	/**
	 * 根据key获得系统配置值(从缓存中获取)
	 * 
	 * @author：lifuyu
	 * 
	 * @param key
	 * @return
	 */
	public static String getSystemConfigValue(String key, String defaultValue)
	{
		return systemCacheKeeper.getSystemConfigValue(key, defaultValue);
	}

	/**
	 * 获取系统配置的值(从缓存中获取)
	 * 
	 * @param key
	 * @param defaultValue
	 *            如果无结果，返回默认值
	 * @return
	 */
	public static String[] getSystemConfigValues(String key, String defaultValue)
	{
		return systemCacheKeeper.getSystemConfigValues(key, defaultValue);
	}

	/**
	 * 获得索引搜索器
	 * 
	 * @param indexName
	 * 
	 * @author kansum
	 */
	public static IndexSearcher getIndexSearcher(String indexName)
	{
		try
		{
			IndexSearcherHolder searcherHolder = IndexSearcherHolder.getInstance();
			if (!searcherHolder.isHoldIndexSearcher(indexName))
			{
				// 持有并打开索引查询器
				String indexRoot = AppContext.getInstance().getSysPropValue(Final.INDEX_ROOT_DIR) + File.separator + indexName;
				searcherHolder.holdIndexSearcher(indexName, indexRoot);
				searcherHolder.openIndexSearcher(indexName);
			}
			return searcherHolder.getIndexSearcher(indexName);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}
}
